(function() {
    'use strict';
    angular.module('weApp.controllers')
            //线路换乘详情
            .controller('transferCtrl', ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', 'weAppDataBase', '$ionicPopup', '$compile', 'showLinePageService', 'localStorageService', '$ionicLoading', '$interval',
                function($scope, $rootScope, $state, $stateParams, $timeout, $http, weAppDataBase, $ionicPopup, $compile, showLinePageService, localStorageService, $ionicLoading, $interval) {

                    if (!$rootScope.lineMoney) {
                        $rootScope.lineMoney = JSON.parse(localStorageService.get("lineMoney"));
                    }

                    var data = $stateParams.data;
                    if (data) {
                        localStorageService.set("searchTrans", JSON.stringify(data));
                    } else {
                        data = JSON.parse(localStorageService.get("searchTrans"));
                    }

                    $scope.tit1 = data.sName;
                    $scope.tit2 = data.eName;
                    $scope.sData = {
                        title: data.sName,
                        point: new BMap.Point(data.sta.location.lng, data.sta.location.lat)
                    };
                    $scope.eData = {
                        title: data.eName,
                        point: new BMap.Point(data.end.location.lng, data.end.location.lat)
                    };

//                if (screen.height)
//                    $('#m-desc').css('height', screen.height + 'px');

                    $scope.route = 'time';

                    $scope.lines = null;
                    $scope.linebus = null;


                    var $sta = $('#txtBusSta');
                    var $end = $('#txtBusEnd');
                    var busStaValue;
                    var busEndValue;

                    //百度地图api
                    var map = new BMap.Map("allmap");    // 创建Map实例
                    map.centerAndZoom($rootScope.cityName, 13);     // 初始化地图,设置中心点坐标和地图级别
                    map.addControl(new BMap.NavigationControl());       // 添加平移缩放控件
                    map.enableScrollWheelZoom();    //启用滚轮放大缩小
                    $scope.searchTransit = function(start, end, type) {
                        $interval.cancel($rootScope.siteTimes);
                        console.log("定时刷新被移除了.");
                        var route = null;
                        var str = null;
                        var str2 = null;
                        var num = 0;

                        var routePolicy = [BMAP_TRANSIT_POLICY_LEAST_TIME, BMAP_TRANSIT_POLICY_LEAST_TRANSFER, BMAP_TRANSIT_POLICY_LEAST_WALKING, BMAP_TRANSIT_POLICY_AVOID_SUBWAYS];
                        if (type == 0) {
                            route = routePolicy[0];
                            $scope.route = 'time';
                        } else if (type == 1) {
                            route = routePolicy[1];
                            $scope.route = 'transfer';
                        } else if (type == 2) {
                            route = routePolicy[2];
                            $scope.route = 'walk';
                        } else {
                            route = routePolicy[0];
                            $scope.route = 'time';
                        }
                        map.clearOverlays();
                        var transit = new BMap.TransitRoute(map, {
                            renderOptions: {map: map, panel: "tran-result"},
                            policy: route,
                            onResultsHtmlSet: function(result) {

                                var res = get_money(result);
                                $('#tran-result2').html(res);
                                // $('#bottom-tabs').hide();
                                // $('#line-bar,#res-line').animate({left: 0});
                                // $('#tran-main').addClass('con-right');
                                $scope.get_time();
                                // $rootScope.siteTimes = setInterval(get_time, 10000);
                                $rootScope.siteTimes = $interval(function() {
                                    $scope.$broadcast("refreshTime");
                                }, 20000);
                            },
                            onSearchComplete: function(result) {
                                if (result) {
                                    num = result.getNumPlans();

                                    if (num > 0) {
                                        var localTran = localStorageService.get("transit") == null ? [] : JSON.parse(localStorageService.get("transit"));
                                        var localTranData = localStorageService.get("transitData") == null ? [] : JSON.parse(localStorageService.get("transitData"));
                                        str = start.title + '@*@' + end.title;
                                        str2 = JSON.stringify($stateParams.data);
                                        if (localTran.indexOf(str) == -1) {
                                            localTran.push(str);
                                            localStorageService.set("transit", JSON.stringify(localTran));
                                            localTranData.push(str2);
                                            localStorageService.set("transitData", JSON.stringify(localTranData));
                                        }
                                    } else {
                                        var myPopu = $ionicPopup.show({
                                            title: "未查询到相应换乘线路",
                                            cssClass: "validate"
                                        });

                                        $timeout(function() {
                                            myPopu.close();
                                        }, 3000);
                                    }
                                }
                            }
                        });

                        transit.search(start, end);
                    }

                    $scope.$on("refreshTime", function(event, data) {
                        var time = Date.parse(new Date());
                        if (!$scope.gtime) {
                            $scope.gtime = time;
                        } else {
                            var tag = time - $scope.gtime;
                            if (tag >= 20000) {
                                $scope.gtime = time;
                            } else {
                                console.log(time);
                                console.log(tag);
                                console.log('不执行get_time');
                                return false;
                            }
                        }
                        console.log(time);
                        console.log(tag);
                        console.log('执行get_time');
                        $scope.get_time();
                    });

                    ///////////////////////////////////////////
                    $scope.searchTransit($scope.sData, $scope.eData);

                    //////////////////////////////////////////
                    function in_array(search, arr) {
                        for (var i in arr) {
                            if (arr[i].line == search) {
                                return arr[i];
                            }
                        }
                        return false;
                    }

                    //插入money
                    function get_money(result) {
                        var lines = [];
                        var line = [];
                        var $res = $(result);
                        var $list = $res.find('.trans-title');
                        var arr = null;
                        var money = null;
                        var str = null;
                        var sName = null;
                        var eName = null;
                        $list.each(function(i, n) {
                            money = 0;
                            var html = $(this).find('p').get(0).innerHTML;
                            var $next = $($(this).find('p').get(1));
                            if (html.indexOf('地铁') >= 0) {
                                // $(this).parent().parent().parent().addClass('noplay');
                                $(this).parent().parent().parent().remove();
                            } else {
                                $(this).parent('div').css({
                                    'border': 'none',
                                    'border-bottom': '1px solid rgb(228, 230, 231)'
                                });
                                //开、结站点
                                var $table = $(this).siblings('div').find('.trans-plan-content');
                                var fir = $(this).siblings('div').find('.nav-st').siblings('div').html();
                                var tag = $table.find('.navtrans-bus-desc').get(0).innerHTML;
                                if (tag.indexOf('步行') >= 0) {
                                    sName = ($table.find('.navtrans-busstation').get(0).innerHTML).replace('站', "");
                                    eName = ($table.find('.navtrans-busstation').get(2).innerHTML).replace('站', "");
                                } else {
                                    sName = fir.replace('站', "");
                                    eName = ($table.find('.navtrans-busstation').get(1).innerHTML).replace('站', "");
                                }

                                arr = html.split(' → ');
                                for (var n in arr) {
                                    if (n >= 0) {
                                        /*if (arr[n].charAt(0) == 'K' || arr[n].charAt(0) == 'k') {
                                         money += 2;
                                         } else {
                                         money += 1;
                                         }*/
                                        if ($rootScope.lineMoney) {
                                            var obj = in_array(arr[n].replace('路', ""), $rootScope.lineMoney);
                                            if (obj) {
                                                money += obj.money * 1;
                                            }
                                        }

                                        if (n == 0) {
                                            lines.push({
                                                lineName: arr[n].replace('路', ""),
                                                startStationName: sName,
                                                endStationName: eName
                                            });
                                            line.push(arr[n]);
                                        }
                                    }
                                }

                                $scope.lines = lines;
                                $scope.linebus = line;
                                if (money * 1 > 0) {
                                    str = '&nbsp;|&nbsp;' + money + '元<br/><label class="site"></label>';
                                } else {
                                    str = '<br/><label class="site"></label>';
                                }

                                $next.append(str);
                            }
                        })
                        return $res;
                    }

                    $scope.get_time = function() {
                        var rootR = {
                            method: 'post',
                            url: $rootScope.rootLocation + '/line/bus/transferPredictList',
                            data: {
                                "cityCode": $rootScope.cityCode,
                                "lines": $scope.lines
                            }
                        };

                        $http(rootR).then(function(boards) {
                            if (boards.data.head.success == "true") {
                                var arr = [];
                                var board = boards.data.data.lineTransferPredicts;
                                for (var i in board) {
                                    if (i >= 0) {
                                        var m = board[i].busStatus * 1;
                                        switch (m) {
                                            case 1:
                                                arr.push({txt: board[i].startStationName + '上车&nbsp;&nbsp;' + $scope.linebus[i] + '&nbsp;&nbsp;<span style="color:red;">即将到站</span>'});
                                                break;
                                            case 2:
                                                arr.push({txt: board[i].startStationName + '上车&nbsp;&nbsp;' + $scope.linebus[i] + '&nbsp;&nbsp;<span style="color:red;">' + board[i].diffSeq + '站/' + board[i].arrivalTime + '分钟</span>后到达'});
                                                break;
                                            case 4:
                                                arr.push({txt: board[i].startStationName + '上车&nbsp;&nbsp;' + $scope.linebus[i] + '&nbsp;&nbsp;<span style="color:red;">等待发车</span>'});
                                                break;
                                            case 5:
                                                arr.push({txt: ''});
                                                break;
                                            default:

                                        }
                                    }
                                }
                                $('#tran-result2 .site').each(function(i) {
                                    if (i >= 0 && arr[i]) {
                                        $(this).html(arr[i].txt);
                                    }
                                })
                                // $rootScope.board = board;
                            }

                        });
                    }

                    $("#tran-result2").delegate(".tranroute-plan-list", "click", function() {
                        var tr = null;
                        $('div.trans_plan_desc').removeClass('line-show');
                        $('#tran-result3').html('');
                        $('#barf').css('z-index', 0);
                        var $div = $(this).find('div.trans_plan_desc');
                        // var tag = $div[0].style.display;
                        // if (tag == 'none') {
                        // $div.addClass('line-show');
                        $('#m-desc').css({top: '380px'});
                        $('#detail-bar,#res-detail').animate({left: 0});
                        $timeout(function() {
                            $('#res-line').hide();
                        }, 300);
                        tr = $(this).html();
                        $('#tran-result3').html(tr);
                        $('#tran-result3 .site').remove();
                        var prev = null;
                        var $prev = null;
                        $scope.cLine = [];
                        $('#tran-result3 .navtrans-bus-icon').each(function(i, n) {
                            var $h = $(this).next('div');
                            var h = $h.html();
                            var t = h.match(/\d+站/g);
                            var str = '';
                            if (t) {
                                t = t[0];
                                var u = t.substring(0, t.length - 1);
                                // if (u * 1 > 1) {
                                if (prev && $prev) {
                                    // prev = prev + '<i class="we-font we-icon-rounddown ic-don" data="' + $scope.cLine.length + '"></i><div class="i-down" style="display: none;"></div>';
                                    // $prev.html(prev);
                                    var sn = $prev.find('.navtrans-busstation').html();

                                    var line = $h.find('.navtrans-busstation').get(0).innerHTML;
                                    var en = $h.find('.navtrans-busstation').get(1).innerHTML;

                                    //拼字符串
                                    str = str + '<tr class="tr-bus"><td><span class="navtrans-bus-icon2 bus"></span><div class="navtrans-bus-desc"><span class="navtrans-busstation">' + sn + '</span>上车</div></td> </tr>';
                                    if (u * 1 > 1) {
                                        $scope.cLine.push({
                                            line: line,
                                            sn: sn,
                                            en: en,
                                            num: u
                                        });
                                        str = str + '<tr class="tr-bus"><td><span class="navtrans-bus-icon2 bline"></span><div class="navtrans-bus-desc"><span>' + line + '</span><span class="ic-donw ic-don" data="' + ($scope.cLine.length - 1) + '">' + u + '站<i class="we-font we-icon-rounddown" ></i></span><div class="n-desc"></div></div></td></tr>';
                                    } else {
                                        str = str + '<tr class="tr-bus"><td><span class="navtrans-bus-icon2 bline"></span><div class="navtrans-bus-desc"><span>' + line + '</span><span class="ic-donw">' + u + '站</span></div></td></tr>';
                                    }
                                    str = str + '<tr class="tr-bus"><td><span class="navtrans-bus-icon2 bus"></span><div class="navtrans-bus-desc"><span class="navtrans-busstation">' + en + '</span>下车</div></td> </tr>';
                                    var par = $(this).parent().parent();
                                    par.after(str);
                                    par.remove();
                                }
                                // }
                            } else {
                                prev = h;
                                $prev = $h;
                            }
                        });
                        // } else {
                        //     $div.removeClass('line-show');
                        // }
                    });
                    var busline = new BMap.BusLineSearch($rootScope.cityName, {
                        onGetBusListComplete: function(result) {
                            if (result) {

                                for (var i = 0, num = result.getNumBusList(); i < num; i++) {
                                    var item = result.getBusListItem(i);
                                    busline.getBusLine(item);
                                }
                                busline.setGetBusLineCompleteCallback(function(lineResults) {
                                    var jsonObj = lineResults;
                                    var BusStaions = [];
                                    var str = '';
                                    for (var i = 0; i < jsonObj.AB.length; i++) {
                                        BusStaions.push(jsonObj.AB[i].name);
                                    }
                                    // console.log("result:" + BusStaions.join(','));
                                    // $scope.busSite.push(BusStaions);
                                    var n = BusStaions.length;
                                    if (n > 0 && $scope.oneBus.sn && $scope.oneBus.en) {
                                        var f = BusStaions.indexOf($scope.oneBus.sn);
                                        var e = BusStaions.indexOf($scope.oneBus.en);
                                        if (f >= 0 && e >= 0 && f < e) {
                                            for (var i = 0; i < n; i++) {
                                                if (i > f && i < e)
                                                    $scope.busSite.push(BusStaions[i]);

                                            }
                                            var p = $scope.busSite.length;
                                            for (var k = 0; k < p; k++) {
                                                str = str + '<div class="n-one"><span class="n-site"></span>' + $scope.busSite[k] + '</div>';
                                            }
                                            $scope.dSite.html(str);
                                            return false;
                                        }
                                    }
                                    $ionicLoading.hide();
                                });
                            }

                        }
                    });
                    $("#tran-result3").delegate(".ic-don", "click", function() {
                        // console.log('ic-don');
                        var i = $(this).attr('data');
                        $scope.dSite = $(this).next('.n-desc');
                        var h = $(this).next('.n-desc').html();
                        if ($scope.cLine[i] && !h) {
                            get_site($scope.cLine[i]);

                        }
                        $scope.dSite.toggle();

                    })
                    function get_site(obj) {
                        $ionicLoading.show({
                            template: '读取中...'
                        })
                        $scope.busSite = [];
                        $scope.oneBus = obj;
                        busline.getBusList(obj.line);
                    }

                    $('#detail-back').click(function() {
                        $('#res-line').show();
                        $('#res-line').attr({style: "left:0"});
                        $('#detail-bar,#res-detail').animate({left: '100%'});
                        $('#barf').css('z-index', 9);
                        $('#m-desc').animate({top: '380px'});
                    })

                    $scope.changeType = function(type) {
                        $scope.searchTransit($scope.sData, $scope.eData, type);
                    }

                    $('#m-nav').click(function() {
                        var top = $('#m-desc').css('top');
                        if (top == '0px') {
                            $('#m-desc').animate({top: '380px'});
                            setTimeout(function() {
                                $('#allmap').css('height','406px');
                            },100)
                        } else {
                            $('#m-desc').animate({top: '0px'});
                            setTimeout(function() {
                                $('#allmap').css('height','330px');
                            }, 100)
                            
                        }
                    })

                    $scope.$on('$destroy', function() {
                        console.log("定时刷新被移除了.");
                        $interval.cancel($rootScope.siteTimes);
                    });
                }])

})();